import api from '@/api/shopcar';
export default {
    namespaced:true,
    state:{
        carList:[] //购物车数据
    },
    mutations:{
        SET_CARLIST(state,payload){
            state.carList = payload.map(item => {
                let target = state.carList.find(val => val.id === item.id);
                item.flag = target ? target.flag : false;
                return item
            })
        },
        //选中单件商品 总价发生变化
        CHANGE_CHECK(state,id){
            const curitem = state.carList.find(item => item.id === id);
            curitem.flag = !curitem.flag;
        }
    },
    actions:{
        getCarList({commit,rootState}){
            commit('user/GET_USERINFO',null,{root:true});
            //获取购物车数据
            api.getCarList({user_id:rootState.user.uid}).then(res => {
                commit('SET_CARLIST',res.data);
            })
        },
        addCar({commit,rootState,dispatch},payload){
            commit('user/GET_USERINFO',null,{root:true});
            api.addCar({...payload,user_id:rootState.user.uid}).then(() => {
                dispatch('getCarList');
            })
        },
        removeCar({commit,rootState,dispatch},payload){
            commit('user/GET_USERINFO',null,{root:true});
            api.removeCar({...payload,user_id:rootState.user.uid}).then(() => {
                dispatch('getCarList');
            })
        },
        delCar({commit,rootState,dispatch},payload){
            commit('user/GET_USERINFO',null,{root:true});
            api.delCar({...payload,user_id:rootState.user.uid}).then(() => {
                dispatch('getCarList');
            })
        }
    },
    getters:{
        sumPrice(state){
            return state.carList.reduce((prev,item) => {
                console.log(state.carList);
                prev += (item.flag ? item.count*item.shopdata.price : 0);
                return prev
            },0)
        }
    }
}